<?php
namespace app\api\service;
use think\Controller;
use think\Db;

class Coupon extends Controller {
    static protected $err_code = 0;
    //创建优惠券接口
    static public function coupon_create($param) {
        if( !isset($param['member_id']) || !isset($param['coupon_type']) || !isset($param['name'])
            || !isset($param['start_get_time'])
            || !isset($param['end_get_time'])
            || !isset($param['start_use_time'])
            || !isset($param['end_use_time'])
            || !isset($param['content'])
            || !isset($param['money'])
            || !isset($param['num'])
            || !isset($param['min_money'])
        ){
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        }

        // 启动事务
        Db::startTrans();
        try{
            $data = [
                'member_id' => $param['member_id'],
                'coupon_type' => $param['coupon_type'],
                'name' => $param['name'],
                'start_get_time' => $param['start_get_time'],
                'end_get_time' => $param['end_get_time'],
                'start_use_time' => $param['start_use_time'],
                'end_use_time' => $param['end_use_time'],
                'content' => $param['content'],
                'money' => $param['money'],
                'num' => $param['num'],
                'min_money' => $param['min_money']
            ];
            Db::table('mob_coupon')->insert($data);
            Db::commit();
            return ['code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }

    // 可领取优惠券列表接口
    static public function coupon_list($param){
        if(!isset($param['member_id']) || !isset($param['coupon_type'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            $where = [
                'member_id' => $param['member_id']
                ,'coupon_type' => $param['coupon_type']
            ];
            $coupon = Db::table('mob_coupon')->where($where)->select();
            return ['data'=>$coupon,'code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }


    // 用户领取优惠券接口
    static public function member_get_coupon($param){
        if(!isset($param['member_id']) || !isset($param['coupon_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        // 启动事务
        Db::startTrans();
        try{
            $coupon = Db::table('mob_coupon')->where('id',$param['coupon_id'])->find();
            if(!$coupon){
                self::$err_code = 400014;
                throw new \Exception('FAULT');
            }
            if( $coupon["start_get_time"]>time() ){
                self::$err_code = 400015;
                throw new \Exception('FAULT');
            }
            if( $coupon["end_get_time"]<time() ){
                self::$err_code = 400016;
                throw new \Exception('FAULT');
            }

            $where = [
                'coupon_id' => $param['coupon_id'],
            ];
            $member_coupon_count = Db::table('mob_member_coupon')->where($where)->count();
            if( $coupon["num"] >= $member_coupon_count ){
                self::$err_code = 400017;
                throw new \Exception('FAULT');
            }

            $data = [
                'member_id' => $param['member_id'],
                'coupon_id' => $param['coupon_id'],
                'status' => 0,
                'get_time' => time(),
                'use_time' => 0
            ];
            Db::table('mob_coupon')->insert($data);
            Db::commit();
            return ['code'=>200,'msg'=> 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }

    }

    // 用户获取可用优惠券列表接口
    static public function member_get_usable_coupon_list($param){
        if(!isset($param['order_id']) ||
            !isset($param['model'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        try{
            $order_id = $param['order_id'];
            $model = $param['model'];
            $field = $join = '';
            $coupon_type = ['in', 0];

            if ($model == 'order_server' || $model == 'order_buy') {
                if ($model == 'order_server') {
                    $coupon_type = ['in', '0, 2'];
                    $join = [['mob_repair r','r.id = o.repair_id', 'LEFT']];
                    $field = 'o.order_price, o.member_id, r.member_id as mid';
                } else if($model == 'order_buy') {
                    $coupon_type = ['in', '0, 1'];
                    $join = [['mob_shop s','r.s = o.shop_id', 'LEFT']];
                    $field = 'o.order_price, o.member_id, s.member_id as mid';
                }
                $order = Db::table('mob_'.$model)->alias('o')->field($field)->join($join)->where('o.id', $order_id)->find();
            } else if ($model == 'scan_pay') {
                $order = Db::table('mob_order_scan_code_pay')->where('id', $order_id)->find(); // 获取扫码支付订单数据
                $coupon_type = ['in', '0, ' . $order['obj_type']];  // 定义可用优惠券类型   为平台发放和对应角色发放
                $order['mid'] = $order['obj_member_id'];
            }

            $where = [
                'mc.member_id' => $order['member_id']
                ,'c.coupon_type' => $coupon_type
                ,'c.member_id' => $order['mid']
                ,'mc.status' => 0
            ];

            $coupon = Db::table('mob_member_coupon')->alias('mc')
                ->field("mc.*, c.content, c.money, c.min_money")
                ->join("mob_coupon c", "mc.coupon_id=c.id")
                ->where($where)
                ->where('c.end_use_time', '> time', time())
                ->where('c.start_use_time', '<= time', time())
                ->where('c.min_money', ['=', 0],['>', $order['order_price']],'or')->select();

            return ['data'=>$coupon,'code'=>200,'msg'=> 'SUCCESS'];

        } catch (\Exception $e) {
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }

    }

    // 统计优惠券数量
    static public function coupon_num($param) {
        if(!isset($param['member_id'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            $unuse = Db::table('mob_member_coupon')->where('member_id', $param['member_id'])->where('status', 0)->count(); // 未使用
            $already_use = Db::table('mob_member_coupon')->where('member_id', $param['member_id'])->where('status', 1)->count(); // 已使用
            $already_over = Db::table('mob_member_coupon')->where('member_id', $param['member_id'])->where('overdue_time', 'lt', time())->where('status', 0)->count(); // 已过期
            return ['code' => 200, 'data' => ['unuse' => $unuse, 'already_use' => $already_use, 'already_over' => $already_over], 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }

    // 根据状态获取优惠券列表
    static public function get_coupon_list_by_status($param) {
        if(!isset($param['member_id']) || !isset($param['status'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            $where['mc.member_id'] = $param['member_id'];
            switch ($param['status']) {
                case 0:
                    $where['mc.status'] = 0;
                    break;
                case 1:
                    $where['mc.status'] = 1;
                    break;
                case 2:
                    $where['mc.status'] = 0;
                    $where['mc.overdue_time'] = ['lt', time()];
                    break;
                default:
                    self::$err_code = 400090;
                    throw new \Exception('FAULT');
                    break;
            }
            $data = Db::table('mob_member_coupon')->alias('mc')->field('c.*, mc.status')
                ->join('mob_coupon c', 'c.id = mc.coupon_id')
                ->where($where)->paginate();
            return ['code' => 200, 'data' => $data, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }

}
